package com.letwal.cmcvnd.anetwork

import com.letwal.cmcvnd.data.RevUserState
import com.google.gson.GsonBuilder
import okhttp3.*
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit

object ApiServiceCreator {

    private val mLoggingInterceptor: HttpLoggingInterceptor =
        HttpLoggingInterceptor(ApiLoggingInterceptor()).apply {
            this.level = HttpLoggingInterceptor.Level.BODY
        }

    private val mGson = GsonBuilder()
        .registerTypeAdapter(RevUserState::class.java, ApiUserStateJsonDeserializer())
        .create()

    private val retrofit =
        Retrofit.Builder()
            .baseUrl(ApiUrl.BASE_URL)
            .client(getHttpClient())
            .addConverterFactory(GsonConverterFactory.create(mGson))
            .build()

    private fun getHttpClient(): OkHttpClient {
        return OkHttpClient.Builder()
            .connectTimeout(60, TimeUnit.SECONDS)
            .writeTimeout(60, TimeUnit.SECONDS)
            .readTimeout(60, TimeUnit.SECONDS)
            .retryOnConnectionFailure(true)
            .connectionPool(ConnectionPool(5, 3, TimeUnit.MINUTES))
            .protocols(listOf(Protocol.HTTP_1_1))
            .addNetworkInterceptor(mLoggingInterceptor)
            .addInterceptor(ResponseInterceptor())
            .build()
    }

    fun <T> create(serviceClass: Class<T>): T = retrofit.create(serviceClass)

    inline fun <reified T> create(): T = create(T::class.java)
}
